package me.zingon.doc.controller;


import me.zingon.doc.exception.ServiceException;
import me.zingon.doc.model.UserProject;
import me.zingon.doc.service.DocumentService;
import me.zingon.doc.model.Document;

import java.util.Date;
import java.util.List;

import me.zingon.doc.service.UserProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;


/**
* Created by ZTCGenerator<zingon@aliyun.com> on 2018-5-31.
*/
@RestController
@RequestMapping("/document")
public class DocumentController extends BaseController{

    @Autowired
    DocumentService documentService;

    @Autowired
    UserProjectService userProjectService;

    @GetMapping("/{url}")
    public Object getDocument(@PathVariable("url")String url) throws ServiceException {
        Document document = documentService.getByUrlWithUser(url,getUser());
        if(document == null){
            document = documentService.getById(0);
        }
        return document;
    }

    @PostMapping("")
    public Object saveDocument(@RequestBody Document document) throws ServiceException {
        List<UserProject> loginUps=userProjectService
                .list(new UserProject()
                        .setUserId(getUser().getId())
                        .setProjectId(document.getProjectId())
                        .setDeleted(false));
        if(loginUps.size() == 0 || loginUps.get(0).getPower().equals("r")){
            throw new ServiceException("user.project.nopower");
        }

        if(document.getId() == null){
            document.setCreateDate(new Date());
            document.setUpdateDate(new Date());
            document.setAuthor(getUser().getNickname());
            documentService.insert(document);
        }else{
            document.setUpdateDate(new Date());
            document.setUpdater(getUser().getNickname());
            documentService.update(document);
        }
        return documentService.getById(document.getId());
    }
}
